package com.cxb.java;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * @Classname ReadWriteLock
 * @Date 2023/4/1 14:49
 * @Created by Administrator
 * @Description TODO
 */
public class ReadWriteLock {

    public static final String ZOOKEEPER_STRING = "127.0.0.1:2181";

    public static CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(ZOOKEEPER_STRING, new ExponentialBackoffRetry(1000, 3));

    public ReadWriteLock() {
        curatorFramework.start();
    }

    public void testZkReadLock() {
        try {
            InterProcessReadWriteLock rwlock = new InterProcessReadWriteLock(curatorFramework, "/curator/rwlock");
            rwlock.readLock().acquire(10, TimeUnit.SECONDS);
            // TODO：一顿读的操作。。。。
            Thread.sleep(2000);
            System.out.println("正在读");
            rwlock.readLock().release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testZkWriteLock() {
        try {
            InterProcessReadWriteLock rwlock = new InterProcessReadWriteLock(curatorFramework, "/curator/rwlock");
            rwlock.writeLock().acquire(10, TimeUnit.SECONDS);
            // TODO：一顿写的操作。。。。
            Thread.sleep(2000);
            System.out.println("正在写");
            rwlock.writeLock().release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ReadWriteLock readWriteLock = new ReadWriteLock();

        readWriteLock.testZkReadLock();

        readWriteLock.testZkWriteLock();
    }

}
